package com.beijing.http.demo02;

import java.io.IOException;
import java.io.OutputStream;
import java.net.InetAddress;
import java.net.Socket;
import java.net.UnknownHostException;
import java.nio.charset.StandardCharsets;

/**
 * @Author Ma Wenqi
 * @Date 2021/3/28 10:30
 * @Version 1.0
 */
//客户端
public class TestClientSocket {
    public static void main(String[] args) {
        //1.要知道服务器的地址

        Socket socket = null;
        OutputStream outputStream = null;
        try {
            InetAddress ServerIp = InetAddress.getByName("127.0.0.1");

            //2.端口号
            int port = 9999;

            //3.创建一个socket连接
            socket = new Socket(ServerIp, port);

            //4.发送消息 IO流
            outputStream = socket.getOutputStream();
            outputStream.write("你好,欢迎狂神说Java".getBytes(StandardCharsets.UTF_8));


        } catch (Exception e) {
            e.printStackTrace();
        } finally {

            if (outputStream != null) {
                try {
                    outputStream.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if (socket != null) {
                try {
                    socket.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }

        }
    }

}
